package com.monkeyk.os.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.monkeyk.os.domain.oauth.AccessToken;
import com.monkeyk.os.oauth.OAuthTokenxRequest;
import com.monkeyk.os.oauth.token.OAuthTokenHandleDispatcher;
import com.monkeyk.os.service.OauthService;
import com.monkeyk.os.util.AJBResponse;
import com.monkeyk.os.util.AJBRspCon;
import com.monkeyk.os.util.BlankUtils;
import com.monkeyk.os.web.WebUtils;

/**
 * 2015/7/3
 * <p/>
 * URL: oauth/token
 *
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("oauth/")
public class OauthTokenController {
	@Autowired
	private OauthService oauthService;

    /**
     * Handle grant_types as follows:
     * <p/>
     * grant_type=authorization_code
     * grant_type=password
     * grant_type=refresh_token
     * grant_type=client_credentials
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @throws OAuthSystemException
     */
    @RequestMapping("token")
    public void authorize(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException {
        try {
            OAuthTokenxRequest tokenRequest = new OAuthTokenxRequest(request);

            OAuthTokenHandleDispatcher tokenHandleDispatcher = new OAuthTokenHandleDispatcher(tokenRequest, response);
            tokenHandleDispatcher.dispatch();

        } catch (OAuthProblemException e) {
            //exception
            OAuthResponse oAuthResponse = OAuthASResponse
                    .errorResponse(HttpServletResponse.SC_FOUND)
                    .location(e.getRedirectUri())
                    .error(e)
                    .buildJSONMessage();
            WebUtils.writeOAuthJsonResponse(response, oAuthResponse);
        }

    }
    
    
    /**
     * token验证
     * @param token
     * @param request
     * @param response
     * @throws OAuthSystemException
     */
    @RequestMapping(value="/tokenValidate", method=RequestMethod.POST)
    @ResponseBody
    public String tokenValidate(@RequestBody JSONObject tokenObject,HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException {
    	int code=AJBRspCon.SUCCESS.getCode();
    	String msg=AJBRspCon.SUCCESS.getMsg();
    	if(BlankUtils.isBlank(tokenObject)){
    		code=AJBRspCon.PARAM_ERROR.getCode();
    		msg=AJBRspCon.PARAM_ERROR.getMsg();
			return WebUtils.renderString(response, AJBResponse.error(code, msg));
    	}
    	String token=(String) tokenObject.get("token");
    	if(BlankUtils.isBlank(token)){
    		code=AJBRspCon.PARAM_ERROR.getCode();
    		msg=AJBRspCon.PARAM_ERROR.getMsg();
			return WebUtils.renderString(response, AJBResponse.error(code, msg));
    	}
    	AccessToken actoken = oauthService.loadAccessTokenByTokenId(token);
    	if (BlankUtils.isNotBlank(actoken)) {
    		boolean tokenExpired = actoken.tokenExpired();
    		if(!tokenExpired){
    			Map<String, Object> rtMap=new HashMap<>();
    			rtMap.put("username", actoken.username());
    			rtMap.put("expires_in", actoken.currentTokenExpiredSeconds());
    			rtMap.put("access_token", actoken.tokenId());
    			rtMap.put("refresh_token", actoken.refreshToken());
    			rtMap.put("token_type", actoken.tokenType());
    			msg="token验证成功";
    			return WebUtils.renderString(response, AJBResponse.successData(msg,rtMap));
    		}else{
    			code=AJBRspCon.TOKEN_EXPIRED.getCode();
    			msg=AJBRspCon.TOKEN_EXPIRED.getMsg();
    			return WebUtils.renderString(response, AJBResponse.error(code, msg));
    		}
    	} else {
    		code=AJBRspCon.TOKEN_NOT_EXIST.getCode();
    		msg=AJBRspCon.TOKEN_NOT_EXIST.getMsg();
    		return WebUtils.renderString(response, AJBResponse.error(code, msg));
    	}
    }
}
